package com.ihm.projetihm_v1.nf.communication;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class CommunicationHTTP
{
	//++++++++++++//
	// ATTRIBUTES //
	//++++++++++++//
	
	private URL mURLServer;
	/**
	 * @return the URL of the server
	 */
	public URL getURLServer(){ return this.mURLServer; }
	

	//++++++++++++++//
	// CONSTRUCTORS //
	//++++++++++++++//
	
	public CommunicationHTTP(URL urlServer)
	{
		this.mURLServer = urlServer;
	}
	

	//+++++++++//
	// METHODS //
	//+++++++++//
	
	/**
	 * 
	 * @param relativePath path relative to server URL
	 * @return the received content from server/relativePath
	 * @throws MalformedURLException if <code>relativePath</code> could not 
	 * be parsed as a URL 
	 * @throws IOException if an error occurs while opening the connection
	 * @throws Exception if the HTTP response code is not 
	 * <code>HttpURLConnection.HTTP_OK</code>
	 */
	public String get(String relativePath) throws Exception
	{
		URL url = new URL(this.mURLServer, relativePath);
		URLConnection connection = url.openConnection();
		HttpURLConnection httpUrlConnection = (HttpURLConnection)connection;
		int responseCode = httpUrlConnection.getResponseCode();
		if(responseCode == HttpURLConnection.HTTP_OK)
		{
			InputStream stream = httpUrlConnection.getInputStream();
			BufferedReader bReader = new BufferedReader(
						new InputStreamReader(stream)
					);
			String line;
			String output = "";
			while((line = bReader.readLine()) != null)
			{
				output += line + System.getProperty("line.separator");
			}
			return output;
		}
		else
		{
			throw new Exception("Responde code not OK (" + responseCode + ")");
		}
	}
	
	/**
	 * return a bitmap from a photo (*.JPG) URL
	 * @param relativePathJPG
	 * @return a bitmap from an URL
	 * @throws MalformedURLException if relativePathJPG does not end with .JPG
	 * or url is a wrong relative path
	 * @throws IOException
	 */
	public Bitmap getBitmapFromURLJPG(String relativePathJPG)
			throws IOException
	{
		if (relativePathJPG.endsWith(".JPG"))
		{
			URL url = new URL(this.mURLServer, relativePathJPG);
			Object content = url.getContent();
			InputStream stream = (InputStream) content;
			Bitmap bitmap = BitmapFactory.decodeStream(stream);
			
			return bitmap;
		}
		else
		{
			throw new MalformedURLException("path must end with .JPG extension");
		}
	}
}
